package com.gongyi.demo01;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

//练习Thread类，实现多线程同步下载图片
public class TestThread2 extends Thread {
    private String url;//网络图片地址
    private String name;//保存的文件名

    public TestThread2(String url, String name) {
        this.url = url;
        this.name = name;
    }

    //下载图片线程的执行体
    @Override
    public void run() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url, name);
        System.out.println("下载了文件名为：" + name);

    }

    public static void main(String[] args) {
        TestThread2 t1 = new TestThread2("https://s.qunarzz.com/f_cms/2021/1638865973476_447461838.png", "qunar.png");
        TestThread2 t2 = new TestThread2("https://imgs.qunarzz.com/vs_ceph_vcimg/5be2601d1f921f166646b817459a2727.jpeg", "1.jpeg");
        TestThread2 t3 = new TestThread2("https://imgs.qunarzz.com/vs_ceph_vcimg/280673be5655fc91ce24ba605c62fe07.jpeg", "2.jpeg");

        //以为是：先下载t1,再下载t2，最后下载t3，其实并不是这样的
        t1.start();
        t2.start();
        t3.start();

    }
}

//下载器
class WebDownloader {
    //下载方法
    public void downloader(String url, String name) {
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));//看源码
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常，downloader方法出现异常");
        }
    }
}
